from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class ecoDA(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        # Python variables
        self.data = {}
        self.RFunctionParam_object = ''
        
        #Unique R variable
        self.setRvariableNames(['discrimin'])
        
        #Inputs
        self.inputs.addInput('id0', 'Group', signals.base.RDataFrame, self.processobject)
        self.inputs.addInput('id1', 'Data table', signals.base.RDataFrame, self.processdiscrimin) 

        #Outputs
        self.outputs.addOutput("id0","DA results", signals.base.RList) #
        
        #GUI
        self.RFunctionParam_group = redRGUI.base.comboBox(self.controlArea, label = 'Select group column')
        self.RFunctionParam_scale = redRGUI.base.radioButtons(self.controlArea,  label = "Scale", buttons = [('FALSE', 'Covariance'),('TRUE','Correlation')],
        setChecked='FALSE',orientation='horizontal')
        self.RFunctionParam_GUI_tabs = redRGUI.base.tabWidget(self.controlArea)
        self.RFunctionParam_GUI_tabsBiplot = self.RFunctionParam_GUI_tabs.createTabPage(name = "Biplot",orientation='vertical')
        self.RFunctionParam_GUI_tabsEigen = self.RFunctionParam_GUI_tabs.createTabPage(name = "Eigenvalues",orientation='vertical')
        self.RFunctionParam_GUI_tabsWeight = self.RFunctionParam_GUI_tabs.createTabPage(name = "Canonical weights",orientation='vertical')
        
        self.RFunctionParam_confReg= redRGUI.base.lineEdit(self.RFunctionParam_GUI_tabsBiplot, label = 'Confidence region ellipses', text = '0.95')
        self.plotAreaBiplot = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsBiplot, label = "Biplot", displayLabel = False)
        self.plotAreaBiplot.resizeCheck.uncheckAll()
        self.plotAreaBiplot.topArea.hide() # hide the graphic options bar
        self.plotAreaEigen = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsEigen, label = "Eigenvalues", displayLabel = False)
        self.plotAreaEigen.topArea.hide() # hide the graphic options bar
        self.plotAreaWeight = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsWeight, label = "Canonical weights", displayLabel = False)
        self.plotAreaEigen.topArea.hide() # hide the graphic options bar
        
        
        #Commit
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)
        
        
    def processobject(self, data):
        if not self.require_librarys(["ade4"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_object=data.getData()
            self.data = data
            self.RFunctionParam_group.update(self.R('names('+self.RFunctionParam_object+')', wantType = 'list'))
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_clust=''
            
    def processdiscrimin(self, data):
        if not self.require_librarys(["ade4"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_discrimin=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_discrimin=''
            
    def commitFunction(self):
        if unicode(self.RFunctionParam_object) == '':
            self.status.setText('No group data.')
            return
        if unicode(self.RFunctionParam_discrimin) == '':
            self.status.setText('No discrimin data.')
            return
        if self.R('is.factor('+unicode(self.RFunctionParam_object)+'$'+unicode(self.RFunctionParam_group.currentId())+')') == False:
            self.status.setText('The selected group column be of class factor.')
            return
        
        self.R('is.factor('+unicode(self.RFunctionParam_object)+'$'+unicode(self.RFunctionParam_group.currentId())+')')
        self.R('pca<-dudi.pca('+unicode(self.RFunctionParam_discrimin)+', scale='+unicode(self.RFunctionParam_scale.getCheckedId())+', scann=F, nf=ncol('+unicode(self.RFunctionParam_discrimin)+'))')

        self.R(self.Rvariables['discrimin']+'<-discrimin(pca, fac='+unicode(self.RFunctionParam_object)+'$'+unicode(self.RFunctionParam_group.currentId())+', scann=F)')
        
        self.R('multEllipse<-sqrt(-2*log(1-'+str(self.RFunctionParam_confReg.text())+'))')
        
        self.plotAreaBiplot.plotMultiple(query = self.Rvariables['discrimin']+'$li , fac='+unicode(self.RFunctionParam_object)+'$'+unicode(self.RFunctionParam_group.currentId())+', cellipse=multEllipse', function = 's.class')
        self.plotAreaEigen.plotMultiple(query = self.Rvariables['discrimin']+'$eig, main="Eigen values"', function = 'barplot')
        self.plotAreaWeight.plotMultiple(query = self.Rvariables['discrimin']+'$fa', function = 's.arrow')
        
        newDA = signals.base.RList(self, data = self.Rvariables['discrimin'], checkVal = False)
        self.rSend("id0", newDA)